package com.qf.controller;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaojian
 */
@RestController
@RequestMapping("/seckill")
public class SecondKillController {

    //1. 准备商品的库存
    public static Map<String,Integer> itemStock = new HashMap<>();

    //2. 准备商品的订单
    public static Map<String,Integer> itemOrder = new HashMap<>();

    @Autowired
    private CuratorFramework cf;

    static{
        //设置库存初始化数据
        itemStock.put("牙刷",10000);
        //设置订单初始化数据
        itemOrder.put("牙刷",0);
    }

    /**
     * 模拟zookeeper分布式锁秒杀下单
     * @param item 商品名称
     */
    @GetMapping("/kill")
    public String kill(String item) throws Exception {

        //============= 创建zookeeper锁对象 ==================
        InterProcessMutex lock = new InterProcessMutex(cf,"/lock");

        //==============zookeeper加锁 ==============
        if(lock.acquire(10, TimeUnit.SECONDS)) {

            //1. 减库存
            Integer stock = itemStock.get(item);
            if(stock <= 0){
                return "商品库存数不足！！！";
            }

            Thread.sleep(100);
            itemStock.put(item,stock - 1);


            //2. 创建订单
            Thread.sleep(100);
            itemOrder.put(item,itemOrder.get(item) + 1);

            //============ zookeeper释放锁 ===============
            lock.release();

            //3. 返回信息
            return "抢购成功！！！" + item + "： 剩余库存数为 - " + itemStock.get(item) + "，订单数为 - " + itemOrder.get(item);
        }else{
            return "没有抢到商品";
        }
    }
}